package com.example.xiaosuan.rfidreadcard;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.cbtService.AndroidSDK.HardwareControler;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    RequestQueue requestQueue;
    private EditText etUserName,etPassWord;
    private TextView tvUserName,tvPassWord;
    private Button btLogin,btCancel;
    EditText rfid_num,moncy_num,add_money,pay_money;
    Button add_bt,pay_bt;
    int serial_fd,ret,cardid;
    long money,rechargemoney,paymoney,maxmoney;
    public static byte[]buf=new byte[14];
    public static byte[]cardinfo=new byte[10];
    public static byte[] addbuf = new byte[4];
    public static byte[] cmdrecharge = new byte[10];
    public static byte[] paybuf= new byte[4];
    public static byte[] cmdpay = new byte[10];

    private final static int MSG_REFRESH=1,MSG_NODATA=0,MSG_ERROR=-1;
    private Thread mThread;
    boolean flagrecharge = false;
    boolean flagpay=false;

    private Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
        switch (msg.what){
            case MSG_REFRESH:
                add_bt.setClickable(true);
                pay_bt.setClickable(true);
                refreshUI();break;
            case MSG_NODATA:
                add_bt.setClickable(false);
                pay_bt.setClickable(false);
                clearUI();break;
            case MSG_ERROR:break;
        }
        }
    };
private Runnable mRecvRunnable=new Runnable() {
    @Override
    public void run() {
        Looper.prepare();
        while (!Thread.interrupted()) {
            ret=HardwareControler.select(serial_fd,2,5);
            if (ret==1){
                HardwareControler.read(serial_fd,buf,1);
                if ((buf[0]&0xFF)==0xEE){
                    HardwareControler.read(serial_fd,buf,1);
                    if ((buf[0]&0xFF)==0xCC){
                        HardwareControler.read(serial_fd,buf,1);
                        if ((buf[0]&0xFF)==0xFE){
                            HardwareControler.read(serial_fd,buf,1);
                            if ((buf[0]&0xFF)==0x01){
                                HardwareControler.read(serial_fd,cardinfo,10);
                                if ((cardinfo[9]&0xFF)==0xFF){
                                        Message msg=Message.obtain();
                                        msg.what=MSG_REFRESH;
                                    mHandler.sendMessage(msg);

                                }
                            }
                        }
                    }
                }
            }
            else if(ret==0)//没有收到串口数据
             {
                Message msg=Message.obtain();
                 msg.what=MSG_NODATA;
                 mHandler.sendMessage(msg);
            }else {
                Message msg=Message.obtain();
                msg.what=MSG_ERROR;
                mHandler.sendMessage(msg);

            }
        }try {
            Thread.sleep(3000);

        }catch (InterruptedException e) {
            e.printStackTrace();
        }
        Looper.loop();

    }
};

    private void clearUI() {
        rfid_num.setText("");
        moncy_num.setText("");
        add_bt.setText("");
        pay_bt.setText("");
    }

    private void refreshUI() {
        if((cardinfo[0]&0xFF)==0x03){
            cardid=((cardinfo[1]&0xFF)<<24)
                    |((cardinfo[2]&0xFF)<<16)
                    |((cardinfo[3]&0xFF)<<8)
                    |((cardinfo[4]&0xFF)<<0);
            money=  ((cardinfo[5]&0xFF)<<24)
                    |((cardinfo[6]&0xFF)<<16)
                    |((cardinfo[7]&0xFF)<<8)
                    |((cardinfo[8]&0xFF)<<0);
            rfid_num.setText(Integer.toHexString(cardid));
            moncy_num.setText(Long.toString(money));
            if (maxmoney > 2147483647) {//充值逻辑判断
                flagrecharge=false;
                Toast.makeText(this, "超过RFID储值范围", Toast.LENGTH_SHORT).show();
            }else {
                flagrecharge=true;
            }
            if (paymoney>money){
                Toast.makeText(this, "余额不足", Toast.LENGTH_SHORT).show();
                flagpay=false;
            }else {
                flagpay=true;
            }

        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        rfid_num= (EditText) findViewById(R.id.editText);
        moncy_num= (EditText) findViewById(R.id.editText2);
        add_money= (EditText) findViewById(R.id.add_money);
        pay_money= (EditText) findViewById(R.id.pay_money);
        add_bt= (Button) findViewById(R.id.add_bt);
        pay_bt= (Button) findViewById(R.id.pay_bt);
        add_bt.setOnClickListener(new ButtinOnClickListener());
        pay_bt.setOnClickListener(new ButtinOnClickListener());

        add_bt.setText("0");
        pay_bt.setText("0");
        HardwareControler._init();
        serial_fd=HardwareControler.openSerialPort("/dev/s3c2410_serial1",115200,8,1);
        mThread=new Thread(mRecvRunnable);
        mThread.start();
        init();
        requestQueue= MyApplication.getsRequestQueue();


    }

    private void init() {


            etUserName = (EditText)findViewById(R.id.etUserName);
            etPassWord = (EditText)findViewById(R.id.etPassWord);
            tvUserName = (TextView)findViewById(R.id.tvusername);
            tvPassWord = (TextView)findViewById(R.id.tvusername);
            btLogin = (Button)findViewById(R.id.btLogin);
            btCancel = (Button)findViewById(R.id.btCancel);
            btLogin.setOnClickListener(this);
            btCancel.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btLogin:
                String url = "http://172.22.232.63:8080/HomeWeb/login?cardid="+rfid_num.getText().toString();
                StringRequest stringRequest = new StringRequest(Request.Method.GET,
                        url,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String s) {
                                if(s.equals("1")){
                                    Intent intent = new Intent(MainActivity.this,HomeActivity.class);
                                    startActivity(intent);
                                }
                                else if(s.equals("0")){
                                    Toast.makeText(MainActivity.this, "卡号不存在！", Toast.LENGTH_SHORT).show();
                                }
                            }
                        },
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError volleyError) {
                                Toast.makeText(MainActivity.this, "网络错误！", Toast.LENGTH_SHORT).show();
                            }
                        }
                );
                requestQueue.add(stringRequest);
                break;
            case R.id.btCancel:
                Toast.makeText(this, "取消登录", Toast.LENGTH_SHORT).show();
                break;
        }

    }

    private class ButtinOnClickListener implements View.OnClickListener {
        @Override
        public void onClick(View view) {
        if(view.getId()==R.id.add_bt){
            flagpay=false;
            rechargemoney=Long.valueOf(add_money.getText().toString());
            maxmoney=money+rechargemoney;
            if (flagrecharge&&rechargemoney!=0){
                addbuf[3]=(byte)((rechargemoney>>24)&0xFF);
                addbuf[2]=(byte)((rechargemoney>>16)&0xFF);
                addbuf[1]=(byte)((rechargemoney>>8)&0xFF);
                addbuf[0]=(byte)((rechargemoney>>0)&0xFF);
                cmdrecharge[0]=(byte)0xCC;
                cmdrecharge[1]=(byte)0xEE;
                cmdrecharge[2]=(byte)0xFE;
                cmdrecharge[3]=(byte)0x01;
                cmdrecharge[4]=(byte)0x01;
                cmdrecharge[5]=addbuf[3];
                cmdrecharge[6]=addbuf[2];
                cmdrecharge[7]=addbuf[1];
                cmdrecharge[8]=addbuf[0];
                cmdrecharge[9]=(byte)0xFF;
                HardwareControler.write(serial_fd,cmdrecharge);
                Toast.makeText(MainActivity.this, "充值", Toast.LENGTH_SHORT).show();
            }else {
                Toast.makeText(MainActivity.this, "chongzhijine", Toast.LENGTH_SHORT).show();
            }
        }else if(view.getId()==R.id.pay_bt){
            flagrecharge=false;
            paymoney=Long.valueOf(pay_money.getText().toString());
            if(paymoney<=money&&paymoney>0){
                paybuf[3]=(byte)((rechargemoney>>24)&0xFF);
                paybuf[2]=(byte)((rechargemoney>>16)&0xFF);
                paybuf[1]=(byte)((rechargemoney>>8)&0xFF);
                paybuf[0]=(byte)((rechargemoney>>0)&0xFF);
                cmdpay[0]=(byte)0xCC;
                cmdpay[1]=(byte)0xEE;
                cmdpay[2]=(byte)0xFE;
                cmdpay[3]=(byte)0x01;
                cmdpay[4]=(byte)0x02;
                cmdpay[5]=addbuf[3];
                cmdpay[6]=addbuf[2];
                cmdpay[7]=addbuf[1];
                cmdpay[8]=addbuf[0];
                cmdpay[9]=(byte)0xFF;
                HardwareControler.write(serial_fd,cmdpay);
                Toast.makeText(MainActivity.this, "支付", Toast.LENGTH_SHORT).show();

            }else {
                if(paymoney>money){
                Toast.makeText(MainActivity.this, "余额不足", Toast.LENGTH_SHORT).show();
            }   if(paymoney<=0){
                    Toast.makeText(MainActivity.this, "请输入支付金额", Toast.LENGTH_SHORT).show();
                }

            }
        }
        }
    }
}
